from PIL import Image
import cv2
import os
import math
#IMG = r'D:\Python\badapple.jpg'


WIDTH = 72
HEIGHT = 50

ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\^`'. ")

badapple = cv2.VideoCapture("BadApple.mkv")

if badapple.isOpened():
    rval,frame = badapple.read()
else:
    rval = False

frame_cnt = 0
outputList = []
n_frames_scale = int(badapple.get(cv2.CAP_PROP_FRAME_COUNT))
print("总帧数 :",n_frames_scale)

def get_char(r, g, b, alpha=256):
    if alpha == 0:
        return ' '
    length = len(ascii_char)
    gray = int(0.2126*r + 0.7152*g + 0.0722*b)
    unit = (256.0 + 1)/length
    return ascii_char[int(gray/unit)]



if __name__ == '__main__':
    while rval:
        im = Image.fromarray(frame)
        im = im.resize((WIDTH, HEIGHT), Image.NEAREST)
        txt = ""
        for i in range(HEIGHT):
            for j in range(WIDTH):
                txt += get_char(*im.getpixel((j,i)))
            txt += '\n'
        #print(txt)
        outputList.append(txt)
        frame_cnt += 1

        st = "已处理" + str(frame_cnt) + "帧"

        a = '*' * int(((frame_cnt/n_frames_scale)*100))
        b = '.' * int(((n_frames_scale - frame_cnt)/n_frames_scale)*100)
        c = (frame_cnt/n_frames_scale) * 100
        print("\r{:^3.0f}%[{}->{}]{}".format(c, a, b, st), end=" ")

        rval,frame = badapple.read()

    for frame_text in outputList:
        os.system("cls")
        print(frame_text)
        # print()
        # print()

        # with open("output.txt", 'w') as f:
        #     f.write(frame_text)